var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pics: [], //照片墙
    picimg: "",
    content: "",
    staffid: 0,
    avaters: [], //商家轮播头图
    avaterimg: '',
    location: 0,
    imgsrc: '',
    isChange: 0,
    changeIndex: [],
    changeArr: [],
    changeInfo:{
      isChange: 0,
      changeIndex:0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.staffid) {
      this.setData({
        staffid: options.staffid
      })
      if (options.location == 1) { //照片墙
        this.getMyPhoto(options.staffid)
        this.setData({
          location: options.location
        })
      }
      if (options.location == 0) { //商家轮播头图
        this.getMyAvaters(options.staffid);
        this.setData({
          location: options.location
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let avaters = this.data.avaters;
    let changeIndex = this.data.changeIndex;
    if (this.data.imgsrc) {
      if (this.data.isChange == 1) {
        avaters.splice(changeIndex[changeIndex.length - 1], 1, this.data.imgsrc);
        this.setData({
          avaters: avaters,
          imgsrc: ''
        })
      } else {
        avaters.push(this.data.imgsrc);
        this.setData({
          avaters: avaters,
          imgsrc: ''
        })
      }
    }
  },

  chooseUploadImg3: function(e) { //这里是选取图片的方法（商家轮播头图裁剪）
    var that = this;
    var avaters = that.data.avaters;
    if (avaters.length >= 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      complete: function(res) {
        if (res.tempFilePaths) {
          wx.navigateTo({
            url: '/pages/weijieke/chooseImage/index?src=' + res.tempFilePaths[0],
          })
        }
      }
    })
  },

  //长按删除图片（照片墙）
  bindlongpressimg3: function(e) {
    var that = this;
    var newpics = that.data.pics;
    var newsImgs = that.data.picimg;
    newsImgs = newsImgs.split(",");
    wx.showModal({
      title: '提示',
      content: '是否删除！',
      success: function(res) {
        if (res.confirm) {
          newpics.splice(e.currentTarget.dataset.id, 1);
          newsImgs.splice(e.currentTarget.dataset.id, 1);
          newsImgs = newsImgs.join(",")
          that.setData({
            pics: newpics
          });
          that.data.picimg = newsImgs;
        }
      }
    })
  },

  //长按删除图片（照片墙）
  bindlongpressimg: function(e) {
    var that = this;
    var newpics = that.data.pics;
    var newsImgs = that.data.picimg;
    newsImgs = newsImgs.split(",");
    wx.showModal({
      title: '提示',
      content: '是否删除！',
      success: function(res) {
        if (res.confirm) {
          newpics.splice(e.currentTarget.dataset.id, 1);
          newsImgs.splice(e.currentTarget.dataset.id, 1);
          newsImgs = newsImgs.join(",")
          that.setData({
            pics: newpics
          });
          that.data.picimg = newsImgs;
        }
      }
    })
  },
  //长按删除轮图片（轮播图）
  bindlongpressimg2: function(e) {
    var that = this;
    var newavaters = that.data.avaters;
    var newsAvaters = that.data.avaterimg;
    newsAvaters = newsAvaters.split(",");
    wx.showModal({
      title: '提示',
      content: '是否删除！',
      success: function(res) {
        if (res.confirm) {
          newavaters.splice(e.currentTarget.dataset.id, 1);
          newsAvaters.splice(e.currentTarget.dataset.id, 1);
          newsAvaters = newsAvaters.join(",")
          that.setData({
            avaters: newavaters
          });
          that.data.avaterimg = newsAvaters;
        }
      }
    })
  },
  changeImg: function(e) {
    var that = this;
    var changeIndex = that.data.changeIndex;
    let imgIndex = e.currentTarget.dataset.id;
    changeIndex.push(imgIndex);
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      complete: function(res) {
        if (res.tempFilePaths) {
          wx.navigateTo({
            url: '/pages/weijieke/chooseImage/index?src=' + res.tempFilePaths[0] + '&isChange=1',
          })
        }
      }
    })
    that.setData({
      changeIndex: changeIndex
    })
  },

  //获取我的照片（照片墙）
  getMyPhoto: function(staffid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/staff/getinfo?id=' + staffid,
      success: function(res) {
        if (res.data.Code == 0) {
          var data = res.data.Data;
          var urlImg = "https://static.711688.net.cn/upload/card/source/thumb600_600/"
          if (data.Imgs) {
            var imgs = data.Imgs.split(',');
            if (imgs.length > 0) {
              for (var i = 0; i < imgs.length; i++) {
                imgs[i] = urlImg + imgs[i];
              }
              that.setData({
                pics: imgs
              })
              that.data.picimg = data.Imgs;
            }
          }
        }
      }
    })
  },


  //提交我的照片（照片墙）
  sendBlogComment: function() {
    var that = this;
    if (that.data.picimg == "") {
      wx.showToast({
        title: '请选择图片！',
      })
      return;
    }
    var info = {
      staffid: that.data.staffid,
      imgs: (that.data.picimg).replace(/^,+|,+$/g, "")
    }
    wx.request({
      url: app.globalData.host + '/api/Staff/AddStaffImgs',
      data: info,
      method: 'POST',
      success: function(res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '提交成功！',
          })
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })
  },


  // 获取商家轮播头图
  getMyAvaters: function(staffid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetSlide?staffId=' + staffid,
      success: function(res) {
        if (res.data.Code == 0) {
          var data = res.data.Data;
          var urlImg = "https://static.711688.net.cn/upload/card/source/thumb600_600/"
          if (data){
            if (data.Value) {
              var imgs = data.Value.split(',');
              if (imgs.length > 0) {
                for (var i = 0; i < imgs.length; i++) {
                  imgs[i] = urlImg + imgs[i];
                }
                that.setData({
                  avaters: imgs
                })
                that.setData({
                  avaterimg: data.Value
                })
              }
            }
          }
        }
      }
    })
  },

  //提交轮播
  sendAvatersComment: function() {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    if (that.data.avaterimg == "") {
      wx.showToast({
        title: '请选择图片！',
      })
      return;
    }
    let content = (that.data.avaterimg).replace(/^,+|,+$/g, "");
    let avaterList = content.split(',');
    let avater = avaterList[0];
    var info = {
      staffId: that.data.staffid,
      content: content
    }
    that.updateStaffAvatar(avater);
    wx.request({
      url: app.globalData.host + '/api/Staff/SetSlide',
      data: info,
      method: 'POST',
      success: function(res) {
        wx.setStorageSync("cardId", cardId);
        if (res.data.Code == 0) {
          wx.showToast({
            title: '提交成功！',
          })
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })
  },

  chooseUploadImg: function(e) { //这里是选取图片的方法（照片墙）
    var that = this;
    var pics = that.data.pics;
    if (pics.length >= 9) {
      wx.showToast({
        title: '最多选择9张！',
      })
      return;
    }
    wx.chooseImage({
      count: 9, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          if (pics.length < 9) {
            pics.push(imgs[i])
          }
        }
        that.setData({
          pics: pics
        });
      },
    })
  },

  companyUploadImg2: function() { //这里触发图片上传的方法（轮播）
    var that = this;
    var avaters = that.data.avaters;
    if (avaters.length == 0) {
      wx.showToast({
        title: '请选择图片！',
      })
      return;
    }
    if (avaters.length > 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否确认提交！',
      success: function(res) {
        if (res.confirm) {
          var newsAvaters = []
          for (var i = 0; i < avaters.length; i++) {
            if (avaters[i].indexOf("https") != 0) {
              newsAvaters.push(avaters[i])
            }
          }
          if (newsAvaters.length > 0) {
            that.uploadimg2({
              url: app.globalData.host + '/api/tool/upload?operation=savecardavater', //这里是你图片上传的接口 
              path: newsAvaters,
            });
          } else {
            that.sendAvatersComment()
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
          return
        }
      }
    })
  },
  // 更新名片头像(个人版)
  updateStaffAvatar: function (avater) {
    wx.showLoading({
      title: '上传中',
      mask: true,
    })
    var that = this;
    var staffId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/Staff/UpdateStaffAvatar',
      data: {
        staffId: staffId,
        avatarUrl: avater
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        } else {
          // that.getInfo(staffId);
          that.data.imgsrc = '';
        }
      },
    })
  },

  companyUploadImg: function() { //这里触发图片上传的方法（照片墙）
    var that = this;
    var pics = that.data.pics;
    if (pics.length == 0) {
      wx.showToast({
        title: '请选择图片！',
      })
      return;
    }
    if (pics.length > 9) {
      wx.showToast({
        title: '最多选择9张！',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否确认提交！',
      success: function(res) {
        if (res.confirm) {
          var newsPics = []
          for (var i = 0; i < pics.length; i++) {
            if (pics[i].indexOf("https") != 0) {
              newsPics.push(pics[i])
            }
          }
          if (newsPics.length > 0) {
            that.uploadimg({
              url: app.globalData.host + '/api/tool/upload?operation=savecardavater', //这里是你图片上传的接口
              path: newsPics, //这里是选取的图片的地址数组
            });
          } else {
            that.sendBlogComment()
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
          return
        }
      }
    })
  },

  //多张图片上传（照片墙）
  uploadimg: function(data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = pic.Data;
        that.data.picimg = that.data.picimg + "," + pic_name;
      },
      fail: (res) => {
        fail++;
      },
      complete: (cp) => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
          that.sendBlogComment();
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },
  //多张轮播头图上传
  uploadimg2: function(data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var avater = JSON.parse(str);
        var avater_name = avater.Data;
        var avaterimg = that.data.avaterimg;
        var changeIndexs = that.data.changeIndex;
        if (that.data.isChange == 1) { //替换轮播图片
          var newAvaterImg = avaterimg.split(",");
          newAvaterImg.splice(changeIndexs[i], 1, avater_name);
          var submitImg = newAvaterImg.toString();
          that.setData({
            avaterimg: submitImg
          })
        }else{
          that.setData({
            avaterimg: avaterimg + "," + avater_name
          })
        }  
      },
      fail: (res) => {
        fail++;
      },
      complete: (cp) => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
          that.sendAvatersComment();
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg2(data);
        }
      }
    });
  },

  cancelBtn: function() {
    wx.navigateBack({
      delta: 1,
    })
  },
})